# -*- coding: UTF-8 -*-
from django import forms
from vdir.models import VDir
from django.shortcuts import get_object_or_404
from models import *
import hashlib

class CreateFileForm(forms.Form):
    parent =  forms.ModelChoiceField(queryset=VDir.objects.all(),\
        empty_label=None,widget=forms.Select(attrs={'class':'form-control'}),required=False)
    
    vf = forms.CharField(\
        widget=forms.widgets.FileInput(attrs={'size':42}),\
            label='文件', required=False)

    def __init__(self,data=None,files=None, *args, **kwargs):
        super(CreateFileForm, self).__init__(data, *args, **kwargs)
        self.files = files


    def clean_vf(self):
        try:
            f = self.files['vf']
            name=f.name

            try:
                parent = self.cleaned_data['parent']
            except:
                raise forms.ValidationError("不能在根目录下创建文件")
        except:
             raise forms.ValidationError('上传文件不能为空')

    def save(self):
        try:
            f=self.files['vf']
            parent = self.cleaned_data['parent']

            from django.conf import settings
            imgfile = open(settings.MEDIA_ROOT+parent.get_full_path()+f.name, 'wb')
            for chunk in f.chunks():
                imgfile.write(chunk) 
            imgfile.close()

            m = hashlib.md5()
            for chunk in f.chunks():
                    m.update(chunk)
            chksum=m.hexdigest()

            try:
                vf=VFile.objects.get(name=f.name)
                if vf.checksum!=chksum:
                    print('ver add')
                    vf.add_ver()
                    vf.update()
                
            except:
                vf=VFile()
                vf.dir=parent
                vf.name=f.name

            vf.checksum=chksum
            vf.save()
            parent.add_ver()
            return vf
        except Exception, e:
            raise e





